資料預處理
from keras.datasets import mnist
from keras.src.utils import np_utils
# 載入數據集,並將其分為訓練集和測試集
(train_feature, train_label), (test_feature, test_label) = mnist.load_data()
#image轉換
train_feature_vector = train_feature.reshape(len(train_feature),28,28,1).astype('float32')
test_feature_vector = test_feature.reshape(len(test_feature),28,28,1).astype('float32')
#image標準化
train_feature_nor = train_feature_vector/255
test_feature_nor = test_feature_vector/255
#轉為One-Hot-Encoding編碼
train_label_onehot = np_utils.to_categorical(train_label)
test_label_onehot = np_utils.to_categorical(test_label)
建立卷積神經網路模型
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,Dropout,Flatten,Dense
model = Sequential()
#卷積層1
model.add(Conv2D(filters=10,kernel_size=(4,4),padding='same',input_shape=(28,28,1),activation='relu'))
#池化層1
model.add(MaxPooling2D(pool_size=(2,2)))
#卷積層2
model.add(Conv2D(filters=20,kernel_size=(4,4),padding='same',activation='relu'))
#池化層2
model.add(MaxPooling2D(pool_size=(2,2)))
#拋棄層
model.add(Dropout(0.2))
#平坦層
model.add(Flatten())
#隱藏層
model.add(Dense(units=256,activation='relu'))
#輸出層
model.add(Dense(units=10,activation='softmax'))
模型訓練
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
xtrain = train_feature_nor.reshape(-1, 28, 28, 1)
train_his = model.fit(x=xtrain,y=train_label_onehot,validation_split=0.2,epochs=10,batch_size=200,verbose=2)
評估模型
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
xtrain = train_feature_nor.reshape(-1, 28, 28, 1)
train_his = model.fit(x=xtrain,y=train_label_onehot,validation_split=0.2,epochs=10,batch_size=200,verbose=2)
圖片預測
import numpy as np
prediction=model.predict(xtest)
predicted_labels = np.argmax(prediction, axis=1)
print(predicted_labels)
---20231004---